package com.bsj.power.system.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bsj.power.common.config.cached.RedisCached;
import com.bsj.power.common.config.exception.ApiException;
import com.bsj.power.common.config.global.JsonResultEnum;
import com.bsj.power.common.config.global.TokenUser;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.constant.UserConstants;
import com.bsj.power.common.def.dto.sys.SystemConfigDTO;
import com.bsj.power.common.def.entity.sys.SystemConfig;
import com.bsj.power.common.mapper.SystemConfigMapper;
import com.bsj.power.common.mapper.UserRoleMapper;
import com.bsj.power.common.util.StpLoginUserUtil;
import com.bsj.power.common.util.StringUtils;
import com.bsj.power.system.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author yinhao
 * @version 1.0
 * @description 系统规则配置
 * @date 2024/8/26
 */
@Slf4j
@Service
public class SystemConfigServiceImpl implements SystemConfigService {


    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Autowired
    private RedisCached redisCached;

    /**
     * 新增或修改配置
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addAndUpdateConf(SystemConfigDTO dto) {
        TokenUser tokenUser = StpLoginUserUtil.getTokenUser();
        Long tokenUserUserId = tokenUser.getUserId();
        Long parentId = tokenUser.getParentId();
        if (parentId != -1) {
            //不是系统超级管理员,无法操作
            throw new ApiException(JsonResultEnum.USER_IS_NOT_ADMIN_UN_OPERATE);
        }
        String phone = dto.getMobilePhone();
        //手机号校验
        if (phone != null && !Validator.isMobile(phone)) {
            throw new ApiException(JsonResultEnum.PHONE_FORMAT_ERROR);
        }
        Long systemConfigId = dto.getSystemConfigId();
        SystemConfig systemConfig = new SystemConfig();
        BeanUtils.copyProperties(dto, systemConfig);
        Integer sys = null;
        if (systemConfigId == null) {
            //新增
            Long count = systemConfigMapper.selectCount(Wrappers.lambdaQuery());
            if (count != null && count >= 1) {
                //目前只能有一条规则
                throw new ApiException(JsonResultEnum.SYSTEM_CONFIG_IS_ONLY);
            }
            systemConfig.setUserId(tokenUserUserId);
            sys = systemConfigMapper.insert(systemConfig);
            redisCached.set(RedisConstant.SYS_CONF_MODE, systemConfig);
        } else {
            //修改,需要可以修改为空值
            LambdaUpdateWrapper<SystemConfig> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(SystemConfig::getSystemConfigId, systemConfigId);
            if (StringUtils.isEmpty(dto.getMobilePhone())) {
                updateWrapper.set(SystemConfig::getMobilePhone, null);
            } else {
                updateWrapper.set(SystemConfig::getMobilePhone, dto.getMobilePhone());
            }
            if (StringUtils.isEmpty(dto.getMail())) {
                updateWrapper.set(SystemConfig::getMail, null);
            } else {
                updateWrapper.set(SystemConfig::getMail, dto.getMail());
            }
            if (dto.getPathRemainTime() == null) {
                updateWrapper.set(SystemConfig::getPathRemainTime, null);
            } else {
                updateWrapper.set(SystemConfig::getPathRemainTime, dto.getPathRemainTime());
            }
            if (dto.getAlarmRunTime() == null) {
                updateWrapper.set(SystemConfig::getAlarmRunTime, null);
            } else {
                updateWrapper.set(SystemConfig::getAlarmRunTime, dto.getAlarmRunTime());
            }
            if (dto.getCrvFailTime() == null) {
                updateWrapper.set(SystemConfig::getCrvFailTime, null);
            } else {
                updateWrapper.set(SystemConfig::getCrvFailTime, dto.getCrvFailTime());
            }
            if (dto.getComposeAlarmTime() == null) {
                updateWrapper.set(SystemConfig::getComposeAlarmTime, null);
            } else {
                updateWrapper.set(SystemConfig::getComposeAlarmTime, dto.getComposeAlarmTime());
            }
            if (dto.getLoginFailNum() == null) {
                updateWrapper.set(SystemConfig::getLoginFailNum, null);
            } else {
                updateWrapper.set(SystemConfig::getLoginFailNum, dto.getLoginFailNum());
            }
            if (dto.getOfflineDur() != null) {
                updateWrapper.set(SystemConfig::getOfflineDur, dto.getOfflineDur());
            }
            if (dto.getDissipateDur() != null) {
                updateWrapper.set(SystemConfig::getDissipateDur, dto.getDissipateDur());
            }
            sys = systemConfigMapper.update(updateWrapper);
            SystemConfig config = systemConfigMapper.selectById(systemConfigId);
            redisCached.set(RedisConstant.SYS_CONF_MODE, config);
        }
        return sys;
    }

    /**
     * 获取规则信息
     * @return
     */
    @Override
    public SystemConfig queryConf() {
        return systemConfigMapper.selectOne(Wrappers.lambdaQuery());
    }
}
